import axios from 'axios'
import qs from 'qs'
import AjaxApi from './api/ajax.api'
import Setting from '../config/defaultSettings'
import { getToken } from '@/utils/auth'

// const reqList = []

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
  baseURL: process.env.VUE_APP_AJAX_BASE_URL,
  // timeout: Setting.request.timeout,
  retry: Setting.request.maxRetry,
  retryDelay: Setting.request.retryDelay,
  // get请求参数格式化
  // stu = {a: 1, b:3} => stu[a]=1&stu[b]=3
  // stu = [1,2,3] => stu[0]=1&stu[1]=2&stu[2]=3
  paramsSerializer: (params) => qs.stringify(params)
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // let cancel
    // config.cancelToken = new axios.CancelToken(c => {
    //   cancel = c
    // })
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }

    // 阻止重复请求。当上个请求未完成时，相同的请求不会进行
    // AjaxApi.stopRepeatRequest(reqList, config.url, cancel)
    return config
  },
  err => Promise.reject(err)
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return AjaxApi.successHandler(response)
  },
  error => {
    return AjaxApi.errorHandler(error)
  }
)

export default service
